package com.liusand.interceptor;

import com.alibaba.fastjson.JSON;
import com.liusand.common.ThreadLocalUtils;
import com.liusand.exception.TokenException;
import com.liusand.pojo.Employee;
import com.liusand.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.plugin.Interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author :liusha
 * packageName :com.liusand.interceptor
 * fileName :TokenInterceptor
 * creationTime :2022/11/21 15:04
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if(!StringUtils.hasText(token)){
            throw new TokenException("token传入失败");
        }
//        Employee employee = employeeService.getByToken(token);
//        if(employee == null){
//            throw new TokenException("token失效");
//        }
        String employeeStr = (String) redisTemplate.opsForValue().get("employee_token:" + token);
        if(employeeStr == null){
            throw new TokenException("token失效");
        }
        Employee employee = (Employee)JSON.parseObject(employeeStr, Employee.class);
        if(employee == null){
            throw new TokenException("token失效");
        }
        ThreadLocalUtils.setEmployee(employee);
        redisTemplate.opsForValue().set("employee_token:" + token, JSON.toJSONString(employee), 30, TimeUnit.MINUTES);
        return true;
    }
}
